package com.windrift.springhibernate.controller;

import com.windrift.common.bean.Option;
import com.windrift.springhibernate.model.CostType;
import com.windrift.springhibernate.service.CostTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xuweigui
 *
 */
@SuppressWarnings("serial")
@Controller
@RequestMapping("/costtype")
public class CostTypeController {

    @Autowired
    private CostTypeService costTypeService;


    @RequestMapping()
    public String list(Model model) {
        List<CostType> costTypes = costTypeService.findAll();
        model.addAttribute("costTypes", costTypes);
        return "manage/CostTypeList";
    }

    @RequestMapping(value="/add")
    @ResponseBody
    public CostType createCostType(@RequestParam("parentId") Integer parentId
            , @RequestParam("name") String name) {
        CostType costType = new CostType();
        costType.setParentId(parentId);
        costType.setName(name);
        costTypeService.add(costType);
        return costType;
    }

    @RequestMapping(value={"remove/{id}","delete/{id}"}, method= RequestMethod.DELETE)
    @ResponseBody
    public void deleteCostType(@PathVariable("id") int id) {
        costTypeService.remove(id);
    }

    //get asset types
    @RequestMapping("/option/{parentId}")
    @ResponseBody
    public List<Option> getCostTypeOption(@PathVariable("parentId") Integer parentId) {
        List<CostType> costTypes  = costTypeService.findChildren(parentId);
        return toOption(costTypes);
    }

    @RequestMapping("/option")
    @ResponseBody
    public List<Option> getCostTypeOption() {
        List<CostType> costTypes = costTypeService.findAll();
        return toOption(costTypes);
    }

    private List<Option> toOption(List<CostType> costTypes) {
        List<Option> options = new ArrayList<Option>();
        for (CostType costType : costTypes) {
            Option option = new Option();
            option.setId(costType.getId());
            option.setName(costType.getName());
            option.setParentId(costType.getParentId());
            options.add(option);
        }

        return options;
    }


    public void setCostTypeService(CostTypeService costTypeService) {
        this.costTypeService = costTypeService;
    }

}
